package com.vay.de.dang.online.util;

import com.vay.de.dang.online.ui.HomeActivity;

import java.io.Closeable;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class UpgradeHelper {

    private static HomeActivity homeActivity;

    public static void init(HomeActivity activity) {
        homeActivity = activity;
    }

    //  NsAppInfoHelper.installApk(mActivity, "com.vi.mpt.fileProvider", file);
    public static void downloadApk(String url, DownloadListener listener) {
        VnExecutors.execTask(() -> downloadFile(url, "vn_" + System.currentTimeMillis() + ".apk", listener));
    }

    private static long downloadFile(String url, String fileName, DownloadListener listener) {

        InputStream input = null;
        FileOutputStream output = null;
        try {

            File downloadDir = new File(homeActivity.getExternalCacheDir(), "download");
            if (!downloadDir.exists()) {
                downloadDir.mkdirs();
            }

            File file = new File(downloadDir, fileName);
            if (!file.exists()) {
                file.createNewFile();
            }

            URL u = new URL(url);
            HttpURLConnection conn = (HttpURLConnection) u.openConnection();
            conn.setConnectTimeout(20 * 60);
            conn.setReadTimeout(30 * 60);

            conn.connect();
            input = conn.getInputStream();
            long totalSize = conn.getContentLength();
            long readSize = 0L;
            output = new FileOutputStream(file);
            byte[] buf = new byte[4096];

            int read;
            while ((read = input.read(buf)) > 0) {
                output.write(buf, 0, read);
                output.flush();
                readSize += read;
                if (listener != null) {
                    downloadProgress(listener, url, totalSize, readSize);
                }
            }

            final long readTotal = readSize;
            if (listener != null) {
                VnHandler.runUI(() -> listener.complete(file));
            }

            return readTotal;
        } catch (Throwable e) {
            e.printStackTrace();
        } finally {
            closeIn(input);
            closeIn(output);
        }

        return -1;
    }

    private static void downloadProgress(DownloadListener listener,
                                         String url, long totalSize, long readSize) {
        VnHandler.runUI(() -> listener.callback(url, totalSize, readSize));
    }

    public static void closeIn(Closeable input) {
        try {
            if (input != null) {
                input.close();
            }
        } catch (Exception var2) {
        }
    }

    public interface DownloadListener {

        void callback(String url, long totalSize, long readSize);

        void complete(File file);
    }
}
